/**
 * Created by Administrator on 2018/12/13.
 */

$(function(){
    var num=8;
    function getajax(){
        $.ajax({
            url: '/contents/review',
            data: {
                contentid: $('#contentId').val(),
                num:num
            },
            beforeSend:function(){
                $("#more_review").html('<img width="20" src="/public/images/loading.gif">');
            },
            complete:function(){

            },
            success: function(result) {
                rdnderComments(result.data);
                if(result.num == result.count || result.num > 8){
                    $("#more_review").html('没有更多了...');
                }
            }
        });
    }
    getajax();

    $("#comments-sub").on('click',function(){
        var contents = $(".comments-txt").find('[name="contents"]').val();
        $.ajax({
            type:'post',
            url:'/contents/review',
            data: {
                contentid: $('#contentId').val(),
                contents:contents
            },
            dataType:'json',
            success: function (result) {
                if(!result.code){
                    getajax();
                    $(".comments-txt").find('[name="contents"]').val('')
                }
            }
        })
    });
    /*$('#more_review').on('click',function(){
        num=num+8;
        getajax();
    })*/
    $(window).scroll(function(){
        // scroll at bottom
        if ($(window).scrollTop() + $(window).height() == $(document).height()) {
            num=num+8;
            getajax();
        }
    });


    function rdnderComments(comments) {
        if(comments.length == 0){
            $("#comments-ul").html('<div class="comments-err">暂时还没有评论，赶紧评论一个吧(#^.^#)</div>');
        }else {
            var html='';
            for(var i = 0; i<comments.length; i++){
                html+='<div class="comments-list"> ' +
                    '<div class="comments-nickname">'+comments[i].nickname+'<span>'+formatDate(comments[i].addTime)+'</span></div> ' +
                    '<div class="comments-box">'+comments[i].comments+
                    '</div> ' +
                    '</div>';
            }
            $("#comments-ul").html(html);
        }
    }

    function formatDate(d) {
        var date1 = new Date(d);
        return date1.getFullYear() + '年' + (date1.getMonth()+1) + '月' + date1.getDate() + '日 ' + date1.getHours() + ':' + date1.getMinutes() + ':' + date1.getSeconds();
    }
});

